package com.szx.usercenter.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author songzx
 * @date 2024/5/12
 * @apiNote
 */
public class JwtHelper {
  // 随机字符串混淆Token
  private static final String tokenSignKey = "uNvs^pML-E";

  /**
   * 生成Token，并保存userID和userName信息
   *
   * @param userId
   * @param userName
   * @return
   */
  public static String createToken(Long userId, String userName) {
    long tokenExpiration = 1000L * 60 * 60 * 24 * 30; // 过期时间，设置30天

    return Jwts.builder()
        .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
        .claim("userId", userId)
        .claim("userName", userName)
        .signWith(SignatureAlgorithm.HS512, tokenSignKey)
        .compressWith(CompressionCodecs.GZIP)
        .compact();
  }

  /**
   * 从token中获取userID
   *
   * @param token
   * @return
   */
  public static Long getUserId(String token) {
    if (StringUtils.isEmpty(token)) return null;
    Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
    Claims claims = claimsJws.getBody();
    Integer userId = (Integer) claims.get("userId");
    return userId.longValue();
  }

  public static Long getLoginId(HttpServletRequest request) {
    return getUserId(getToken(request));
  }

  public static String getToken(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    return token;
  }

  /**
   * 从token中获取用户姓名
   *
   * @param token
   * @return
   */
  public static String getUserName(String token) {
    if (StringUtils.isEmpty(token)) return "";
    Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
    Claims claims = claimsJws.getBody();
    return (String) claims.get("userName");
  }

  /**
   * 查看Token是否过期
   *
   * @param token
   * @return false 未过期，true 已过期
   */
  public static Boolean tokenExpired(String token) {
    try {
      Claims claims = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
      Date expiration = claims.getExpiration();
      Date currentDate = new Date();
      return expiration.before(currentDate);
    } catch (Exception ex) {
      return true;
    }
  }
}
